$(document).ready(function(){
	// 导入模块
	const api = require("../modules/api.js");
	const Modal = require("../modules/modal.js");
	// 定义变量
	const form = {
		phone: "",
		code: ""
	};
	const modal = new Modal();

	// 监测数据变化
	$("#phone").bind("change property", function(e){
		form.phone = $("#phone").val();
	});
	$("#code").bind("change property", function(e){
		form.code = $("#code").val();
	});
	
	function phone_validate(){
		if(!form.phone){
			modal.confirm({title: "提示信息", content: "请填写手机号！"});
			return false;
		};
		if(!/^1[3|4|5|7|8]\d{9}$/.test(form.phone)){
			modal.confirm({title: "提示信息", content: "请填写合法的手机号！"});
			return false;
		};
		return true;
	};

	function code_validate(){
		if(!form.code){
			modal.confirm({title: "提示信息", content: "请填写验证码！"});
			return false;
		};
		return true;
	};
	
	let is_code_send = false;
	// 发送验证码
	$("#sendCode").click(function(){
		if(phone_validate() && !is_code_send){
			is_code_send = true;
			api.user_getCode({phone: form.phone}).then(res=>{
				if(res.code == "0"){
					let time = 10;
					$(".code").text(`${time}s`).addClass("code-active");
					let timer = setInterval(()=>{
						time -= 1;
						$(".code").text(`${time}s`);
						if(time < 1){
							$(".code").removeClass("code-active").text("获取验证码");
							clearInterval(timer);
							is_code_send = false;
						};
					}, 1000);
				}else{
					modal.confirm({title: "提示信息", content: res.errorMsg});
				};
			});
			
		};
	});
	// 提交
	$("#submit").click(function(){
		if(phone_validate() && code_validate()){
			console.log(form);
			api.user_login({phone: form.phone, code: form.code}).then(res=>{
				if(res.code == "0"){
					window.location.href = "/h5/personal";
				}else{
					modal.confirm({title: "提示信息", content: res.errorMsg});
				};
			});
		}
	});	
});